package cn.cmkj.auction.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import org.apache.commons.lang.StringEscapeUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.GoodsOfOrderAdapter;
import cn.cmkj.auction.app.BaseActivity;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.Address;
import cn.cmkj.auction.data.http.Shuhua;
import cn.cmkj.auction.data.http.ShuhuaOrder;
import cn.cmkj.auction.data.model.AliPayResult;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.Utils;
import cn.cmkj.auction.utils.alipay.OrderInfoUtil2_0;
import cn.cmkj.auction.widget.AlertDialog;
import cn.cmkj.auction.widget.MyScrollView;

/**
 * Created by cunguoyao on 2017/9/20.
 */
@ContentView(R.layout.activity_order_detail)
public class OrderDetailActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    @ViewInject(R.id.common_title)
    private RelativeLayout titleLayout;
    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.swipeRefreshLayout)
    private SwipeRefreshLayout swipeRefreshLayout;
    @ViewInject(R.id.scrollView)
    private MyScrollView scrollView;
    private int height;

    @ViewInject(R.id.order_status_layout)
    private LinearLayout orderStatusLayout;
    @ViewInject(R.id.order_code_layout)
    private LinearLayout orderCodeLayout;
    @ViewInject(R.id.order_text_code)
    private TextView textOrderCode;
    @ViewInject(R.id.order_text_time)
    private TextView textOrderTime;

    @ViewInject(R.id.order_address_layout)
    private LinearLayout orderAddressLayout;
    @ViewInject(R.id.order_address_layout_name)
    private RelativeLayout orderAddressLayoutName;
    @ViewInject(R.id.order_address_receive_name)
    private TextView orderAddressReceiveName;
    @ViewInject(R.id.order_address_receive_phone)
    private TextView orderAddressReceivePhone;
    @ViewInject(R.id.order_address_receive_location)
    private TextView orderAddressReceiveLocation;

    @ViewInject(R.id.order_goods_list)
    private RecyclerView orderGoodsListView;

    @ViewInject(R.id.order_layout_zb)
    private RelativeLayout orderLayoutZb;
    @ViewInject(R.id.order_text_zb)
    private TextView orderTextZb;
    @ViewInject(R.id.order_layout_yhq)
    private RelativeLayout orderLayoutYhq;
    @ViewInject(R.id.order_text_yhq_price)
    private TextView orderTextYhq;
    @ViewInject(R.id.order_layout_yf)
    private RelativeLayout orderLayoutYf;
    @ViewInject(R.id.order_text_yf_note)
    private TextView orderTextYfNote;
    @ViewInject(R.id.order_text_yf_price)
    private TextView orderTextYf;
    @ViewInject(R.id.order_layout_total_price)
    private RelativeLayout orderLayoutTotalPrice;
    @ViewInject(R.id.order_text_total_price)
    private TextView orderTextTotalPrice;

    @ViewInject(R.id.order_should_pay_price)
    private TextView orderShouldPayPrice;

    @ViewInject(R.id.rd_alipay)
    private RadioButton rdAlipay;
    @ViewInject(R.id.btn_cancel)
    private Button btnCancel;
    @ViewInject(R.id.btn_submit)
    private Button btnSubmit;
    public static final String FROM = "from_page";
    public static final int FROM_PRE_ORDER = 1;
    public static final int FROM_ORDER_LIST = 2;

    private int fromPage;
    private ShuhuaOrder order;
    private List<Shuhua> shuhuaList;
    private GoodsOfOrderAdapter goodsOfOrderAdapter;

    public static final String RSA2_PRIVATE = "";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    AliPayResult payResult = new AliPayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(OrderDetailActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(OrderDetailActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        fromPage = getIntent().getIntExtra(FROM, FROM_ORDER_LIST);
        order = (ShuhuaOrder)getIntent().getSerializableExtra("order");
        if(order == null) {
            finish();
            return;
        }
        shuhuaList = new ArrayList<>();
        //为SwipeRefreshLayout设置监听事件
        swipeRefreshLayout.setOnRefreshListener(this);
        if(fromPage == FROM_PRE_ORDER) {
            titleText.setText("确认订单");
            swipeRefreshLayout.setEnabled(false);
            fillData(order);
            rdAlipay.setChecked(true);
        }else if(fromPage == FROM_ORDER_LIST) {
            titleText.setText("订单详情");
            swipeRefreshLayout.setEnabled(true);
            //进入页面自动刷新 请求接口获取订单详情数据
            swipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(true);
                    fetchData();
                }
            });
            rdAlipay.setChecked(true);
        }
        titleBack.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
    }

    @Override
    public void onRefresh() {
        fetchData();
    }

    private void fetchData() {
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.orderDetail);
            params.addParameter("order_id", order.getOrderId());
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    swipeRefreshLayout.setRefreshing(false);
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        order = ShuhuaOrder.parseFromJsonDetail(json);
                        fillData(order);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    swipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void cancel(CancelledException e) {
                    swipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void finished() {
                    swipeRefreshLayout.setRefreshing(false);
                }
            });
        }
    }

    private void fillData(ShuhuaOrder order) {
        LogUtil.e("" + System.currentTimeMillis());
        if(order == null)return;
        if(fromPage == FROM_PRE_ORDER) {
            orderStatusLayout.setVisibility(View.GONE);
            orderCodeLayout.setVisibility(View.GONE);

            orderLayoutZb.setVisibility(View.GONE);
            orderLayoutYhq.setVisibility(View.VISIBLE);
            orderTextYhq.setText("￥" + order.getTotalDiscount());
            orderLayoutYf.setVisibility(View.VISIBLE);
            orderTextYfNote.setText(order.getShipping().dt_name);
            orderTextYf.setText("￥" + order.getShipping().firstprice);
            orderTextTotalPrice.setText("￥" + order.getTotalShouldPay());
        }else if(fromPage == FROM_ORDER_LIST) {
            orderStatusLayout.setVisibility(View.GONE);
            orderCodeLayout.setVisibility(View.VISIBLE);
            textOrderCode.setText(order.getOrderId());
            textOrderTime.setText(Utils.formatDate(order.getOrderTime()));

            orderLayoutZb.setVisibility(View.GONE);
            orderLayoutYhq.setVisibility(View.VISIBLE);
            orderTextYhq.setText("￥" + order.getTotalDiscount());
            orderLayoutYf.setVisibility(View.VISIBLE);
            orderTextYfNote.setText(order.getShipping().dt_name);
            orderTextYf.setText("￥" + order.getShipping().firstprice);
            orderTextTotalPrice.setText("￥" + order.getTotalShouldPay());

            btnCancel.setVisibility(View.GONE);
            if("未支付".equals(order.getPayStatusStr())) {
                btnSubmit.setEnabled(true);
                btnSubmit.setText("立即支付");
            }else {
                btnSubmit.setEnabled(false);
                btnSubmit.setText(order.getPayStatusStr());
            }
        }
        orderAddressLayout.setVisibility(View.VISIBLE);
        Address orderAddress = order.getOrderAddress();
        if(orderAddress != null) {
            orderAddressReceiveName.setText(orderAddress.getName());
            orderAddressReceivePhone.setText(orderAddress.getMobile());
            orderAddressReceiveLocation.setText(orderAddress.getAddr());
        }else {
            orderAddressLayoutName.setVisibility(View.GONE);
            orderAddressReceiveLocation.setText("请选择您的收货地址~~");
            orderAddressReceiveLocation.setGravity(Gravity.CENTER);
            orderAddressReceiveLocation.setTextSize(15);
            orderAddressReceiveLocation.setTextColor(getResources().getColor(R.color.b_33));
        }
        orderAddressLayout.setOnClickListener(this);

        shuhuaList = order.getShuhuaList();
        goodsOfOrderAdapter = new GoodsOfOrderAdapter(this, shuhuaList, 1);
        orderGoodsListView.setLayoutManager(new LinearLayoutManager(this));
        orderGoodsListView.setAdapter(goodsOfOrderAdapter);

        orderTextTotalPrice.setText("￥"+order.getTotalShouldPay().doubleValue());
        orderShouldPayPrice.setText("￥"+order.getTotalShouldPay().doubleValue());
    }

    private void orderCreate() {
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.orderCreate);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            params.addParameter("isfastbuy", "true");
            params.addParameter("def_addr_id", "");
            Shuhua shuhua = order.getShuhuaList().get(0);
            params.addParameter("cart[goods_id]", shuhua.getId());
            params.addParameter("cart[product_id]", shuhua.getProductId());
            Address address = order.getOrderAddress();
            params.addParameter("address[addr_id]", address.getId());
            params.addParameter("address[area]", address.getAddr());
            params.addParameter("shipping[id]", order.getShipping().dt_id);
            params.addParameter("payment[currency]", "CNY");
            params.addParameter("payment[pay_app_id][pay_app_id]", order.getPayment().payment_id);
            params.addParameter("payment[pay_app_id][payment_name]", order.getPayment().payment_name);
            params.addParameter("coupon", "");//优惠券码
            params.addParameter("memo", "");//订单备注 客户留言
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            String orderId = json.optString("order_id");
                            order.setOrderId(orderId);
                            getAlipayOrder(orderId);
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(OrderDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(OrderDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void getAlipayOrder(final String orderId) {
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.getOrderForAlipay);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            params.addParameter("order_id", orderId);
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        String orderInfo = jsonStr.optString("data");
                        if(orderInfo != null && !"".equals(orderInfo)) {
                            aliPay(orderInfo);
                        }
                        String toast = jsonStr.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(OrderDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(OrderDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void aliPay(final String orderInfos) {
        final String orderInfo = StringEscapeUtils.unescapeHtml(orderInfos);
        LogUtil.e("--orderInfos--orderInfo=" + orderInfo);
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderDetailActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                LogUtil.i("--OrderDetailActivity--msp=" + result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back:
                confirmLeave();
                break;
            case R.id.order_address_layout:
                Intent intent = new Intent(this, UserAddressActivity.class);
                intent.putExtra(UserAddressActivity.FROM, UserAddressActivity.FROM_ORDER);
                startActivityForResult(intent, 1);
                break;
            case R.id.btn_cancel:
                confirmLeave();
                break;
            case R.id.btn_submit:
                if(order.getOrderAddress() == null) {
                    Toast.makeText(this, "请选择收件地址~~", Toast.LENGTH_SHORT).show();
                }else {
                    if(fromPage == FROM_PRE_ORDER) {
                        orderCreate();
                    }else if(fromPage == FROM_ORDER_LIST) {
                        getAlipayOrder(order.getOrderId());
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                Address orderAddress = (Address)data.getSerializableExtra("address");
                if(orderAddress != null && order != null) {
                    order.setOrderAddress(orderAddress);
                    orderAddressLayoutName.setVisibility(View.VISIBLE);
                    orderAddressReceiveName.setText(orderAddress.getName());
                    orderAddressReceivePhone.setText(orderAddress.getMobile());
                    orderAddressReceiveLocation.setText(orderAddress.getAddr());
                    orderAddressReceiveLocation.setGravity(Gravity.LEFT | Gravity.TOP);
                    orderAddressReceiveLocation.setTextSize(13);
                    orderAddressReceiveLocation.setTextColor(getResources().getColor(R.color.b_80));
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        confirmLeave();
    }

    private void confirmLeave() {
        AlertDialog loginDialog = new AlertDialog(this);
        loginDialog.builder().setTitle("提示").setMsg("好东西不等人，请三思而行~~")
                .setCancelable(true).setNegativeButton("我再想想", null)
                .setPositiveButton("残忍离开", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).show();
    }
}
